package com.wude.guild;

import android.annotation.SuppressLint;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.blankj.utilcode.util.ServiceUtils;
import com.mc.developmentkit.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import com.wude.bean.AboutUs;
import com.wude.bean.AppInfo;
import com.wude.bean.SettingInfo;
import com.wude.guild.dialog.VersionDialog;
import com.wude.guild.face.HomeMenuFace;
import com.wude.guild.fragment.CommentariesFragment;
import com.wude.guild.fragment.GeneralizeFragment;
import com.wude.guild.fragment.HomeFragment;
import com.wude.guild.fragment.WelfareFragment2;
import com.wude.guild.fragment.WelfareFragment3;
import com.wude.guild.fragment.mineFragment;
import com.wude.guild.manager.DownloadManager;
import com.wude.guild.servercore.mints.MintsBaseActivity;
import com.wude.guild.views.HomeButtomMenu;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.http.NetWorkBroadcast;
import com.wude.tools.DbUtils;
import com.wude.tools.FileUtils;
import com.wude.tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends MintsBaseActivity implements HomeMenuFace {
    LinearLayout ll_menu;

    private static NetWorkBroadcast networkBroadcast = new NetWorkBroadcast();
    private long exitTime;
    public static MainActivity mActivity;
    private DbManager db;
    private HomeButtomMenu menu;

    public int dayLootery = 1;// 	每日抽奖 1-未领取 0-已领取
    public int ver = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setContentView(R.layout.activity_main);
        initView();
        HttpCom.POST(bhandler, HttpCom.getVisonURL(), null, false);  //获取APP版本的请求
    }


    private void initView() {
        ll_menu = findView(R.id.ll_menu);
        menu = new HomeButtomMenu(this, this);
        ll_menu.addView(menu);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshRedIcon();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void refreshRedIcon() {
        Map<String, String> map = new HashMap<>();
        map.put("token", Utils.getLoginUser() == null ? "" : Utils.getLoginUser().token);
        HttpCom.POST(redHandler, HttpCom.getGetRedIconStatus(), map, false);
    }

    /**
     * 福利红点
     */
    @SuppressLint("HandlerLeak")
    Handler redHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (menu != null) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            int dayFlow = data.getInt("dayFlow");
                            dayLootery = data.getInt("dayLottery");

                            if (dayFlow == 0 && dayLootery == 0)
                                menu.hashNew(false);
                            else
                                menu.hashNew(true);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络错误");
                    break;
            }
        }
    };

    @Override
    protected int getFragmentContainerId() {
        return R.id.container;
    }

    /**
     * 首页
     */
    @Override
    public void home() {
        popToRoot(null);
        pushFragmentToBackStack(HomeFragment.class, null);
    }

    /**
     * 动态
     */
    @Override
    public void message() {
        popToRoot(null);
        pushFragmentToBackStack(CommentariesFragment.class, null);
    }

    /**
     * 福利
     */
    @Override
    public void welfare() {
        popToRoot(null);
        pushFragmentToBackStack(WelfareFragment3.class, null);
    }

    /**
     * 分享
     */
    @Override
    public void shared() {
        popToRoot(null);
        pushFragmentToBackStack(GeneralizeFragment.class, null);
    }

    /**
     * 我的
     */
    @Override
    public void mine() {
        popToRoot(null);
        pushFragmentToBackStack(mineFragment.class, null);
    }

    public static void unRegisterNetworkReceiver() {
        if (mActivity != null) {
            mActivity.unregisterReceiver(networkBroadcast);
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.close_left_in, R.anim.close_left_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterNetworkReceiver();
    }

    /**
     * 请求权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showToast("没有权限无法下载游戏");
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Utils.TS("再按一次退出程序！");
                List<AppInfo> alluser = DownloadManager.getDownloadingAppList();
                if (alluser != null) {
                    for (int i = 0; i < alluser.size(); i++) {
                        AppInfo appInfo = alluser.get(i);
                        DownloadManager.getInstance().pause(appInfo);
                    }
                }
                exitTime = System.currentTimeMillis();
            } else {
                if (ServiceUtils.isServiceRunning(this, HttpCom.getDownServer())) {
                    ServiceUtils.stopService(this, DownloadManager.class);
                }
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 请求关于我们/版本号是否有更新
     */
    @SuppressLint("HandlerLeak")
    Handler bhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        AboutUs aboutUs = HttpUtils.DNSAboutUs(msg.obj.toString());
                        int i = Utils.verison_update(aboutUs.version_hao, aboutUs.versionUrl);
                        switch (i) {
                            case 1:
                                ver = 1;
                                break;
                            case 2:
                                break;
                            case 3:
                                ToastUtil.showToast("后台版本号格式填写有误");
                                break;
                            case 4:
                                ToastUtil.showToast("服务端版本小于本地版本");
                                break;
                        }
                        if (aboutUs != null) {
                            aboutUs.id = 2;
                            DbManager db = DbUtils.getDB();
                            db.saveOrUpdate(aboutUs);
                        }

                        Log.e("ver的值", ver + "");
                        if (ver == 1) {
                            VersionDialog versionDialog = new VersionDialog(MainActivity.this, R.style.loading_dialog, aboutUs.version_log);
                            versionDialog.setCancelable(false);
                            versionDialog.show();
                        } else {
                            FileUtils.verifyStoragePermissions(MainActivity.this);
                            mActivity = MainActivity.this;
                            db = DbUtils.getDB();
                            try {
                                SettingInfo findById = db.findById(SettingInfo.class, 1);
                                if (findById != null && findById.wlti == 2) {
                                    registerNetworkReceiver();
                                }
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }

                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:

                    break;
            }
        }
    };

    public static void registerNetworkReceiver() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        if (mActivity != null) {
            mActivity.registerReceiver(networkBroadcast, filter);
        }
    }
}
